<template>
  <div class="app-container">
    <!-- 页面头部信息 -->
    <div class="process-header">
      <div class="process-info">
        <div class="info-item">
          <span class="label">流程名称:</span>
          <span class="value">{{ processInfo.processName || '未设置' }}</span>
        </div>
        <div class="info-item">
          <span class="label">流程标识key:</span>
          <span class="value">{{ processInfo.processKey || '未设置' }}</span>
        </div>
        <div v-if="processInfo.description" class="info-item">
          <span class="label">流程描述:</span>
          <span class="value">{{ processInfo.description }}</span>
        </div>
      </div>
      <div class="header-actions">
        <el-button @click="handleCancel">返回</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </div>

    <!-- 流程配置区域 -->
    <div class="process-config">
      <div class="flowchart-container">
        <div class="flowchart">
          <!-- 开始节点 -->
          <div class="node start-node">
            <span>开始</span>
          </div>

          <!-- 动态审批节点 -->
          <div v-for="(node, index) in approvalNodes" :key="node.id" class="node-container">
            <div class="arrow"></div>
            <div
              class="node approval-node"
              :class="{ active: selectedNodeId === node.id }"
              @click="handleNodeClick(node)"
            >
              <span>{{ node.name }}</span>
              <div class="node-actions">
                <el-link :underline="false" type="primary" @click.stop="handleEditNode(node)">
                  编辑
                </el-link>
                <el-link :underline="false" type="primary" @click.stop="handleDeleteNode(index)">
                  删除
                </el-link>
              </div>
            </div>
          </div>

          <!-- 添加节点按钮 -->
          <div class="node-container">
            <div class="arrow"></div>
            <div class="add-node" @click="handleAddNode">
              <el-icon><Plus /></el-icon>
              <span>添加审批节点</span>
            </div>
          </div>

          <!-- 结束节点 -->
          <div class="node-container">
            <div class="arrow"></div>
            <div class="node end-node">
              <span>结束</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 节点编辑弹窗 -->
    <NodeEditDialog
      v-model:visible="nodeEditVisible"
      :node-data="currentNodeData"
      @confirm="handleNodeEditConfirm"
    />
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import NodeEditDialog from './components/NodeEditDialog.vue'
import {
  getApprovalConfigDetail
} from '@/api/system/approval'
// 路由
const route = useRoute()
const router = useRouter()

// 流程信息
const processInfo = reactive({
  processName: '',
  processKey: '',
  description: '', // 添加描述字段
  templateId: ''   // 添加模板ID
})

// 审批节点数据
const approvalNodes = ref([])

// 当前选中的节点ID
const selectedNodeId = ref(null)

// 节点编辑相关
const nodeEditVisible = ref(false)
const currentNodeData = ref({})

// 节点ID计数器
let nodeIdCounter = 1
/** 加载审批节点数据 */
const loadApprovalNodes = (nodes) => {
  // 重置节点ID计数器
  nodeIdCounter = 1
  
  if (Array.isArray(nodes) && nodes.length > 0) {
    // 根据返回的数据结构转换节点格式
    approvalNodes.value = nodes.map(node => {
      // 根据approverType转换为前端所需格式
      const nodeData = {
        id: nodeIdCounter++,
        nodeId: node.nodeId, // 保留原始节点ID
        name: node.nodeName, // 使用nodeName作为节点名称
        approverType: getApproverType(node.approverType), // 转换审批人类型
        nodeOrder: node.nodeOrder // 保留节点顺序
      }
      
      // 根据审批人类型设置对应的审批人信息
      if (node.approverType === '01') { // 指定用户
        nodeData.approverUsers = [{ id: node.approverValue, name: node.approverTypeName || '用户' }]
      } else if (node.approverType === '02') { // 角色
        nodeData.approverRole = node.approverTypeName || '角色'
      } else if (node.approverType === '03') { // 部门
        nodeData.approverDepartment = node.approverTypeName || '部门'
      }
      
      // 保留其他原始属性
      nodeData.canEdit = node.canEdit !== false
      nodeData.canTransfer = node.canTransfer !== false
      nodeData.isRequired = node.isRequired !== false
      
      return nodeData
    }).sort((a, b) => a.nodeOrder - b.nodeOrder) // 按节点顺序排序
  } else {
    approvalNodes.value = []
  }
}

/** 转换审批人类型代码为前端所需格式 */
const getApproverType = (typeCode) => {
  const typeMap = {
    '01': 'user',     // 指定用户
    '02': 'role',     // 角色
    '03': 'department' // 部门
  }
  return typeMap[typeCode] || 'user'
}
// 监听路由参数变化，更新流程信息
watch(
  () => route.params,
  (newParams) => {
    if (newParams.approvals) {
      getApprovalConfigDetail(newParams?.approvals).then(res => {
        if (res.code === 200 && res.data) {
          const data = res.data
          
          // 更新流程信息
          processInfo.processName = data.templateName || '' // 使用templateName作为流程名称
          processInfo.processKey = data.templateCode || '' // 使用templateCode作为流程标识
          // 加载审批节点数据（从nodes数组）
          loadApprovalNodes(data.nodes || [])
        } else {
          ElMessage.warning('获取流程详情失败')
        }
      }).catch(() => {
        ElMessage.error('获取流程详情失败')
      })
    }
  },
  { immediate: true, deep: true }
)

/** 点击节点 */
const handleNodeClick = (node) => {
  selectedNodeId.value = node.id
}

/** 编辑节点 */
const handleEditNode = (node) => {
  console.log('编辑节点', node);
  
  currentNodeData.value = { ...node }
  nodeEditVisible.value = true
}

/** 删除节点 */
const handleDeleteNode = async (index) => {
  try {
    await ElMessageBox.confirm('确定要删除这个审批节点吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    approvalNodes.value.splice(index, 1)
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

/** 格式化审批人显示信息 */
const formatApprovers = (node) => {
  if (!node) return ''
  
  if (node.approverType === 'user') {
    return node.approverUsers?.map(user => user.name).join('、') || ''
  } else if (node.approverType === 'role') {
    return node.approverRole || ''
  } else if (node.approverType === 'department') {
    return node.approverDepartment || ''
  }
  return ''
}

/** 添加节点 */
const handleAddNode = () => {
  const newNode = {
    id: nodeIdCounter++,
    name: '新审批节点',
    approverType: 'user',
    approverUsers: []
  }

  approvalNodes.value.push(newNode)

  // 自动打开编辑弹窗
  currentNodeData.value = { ...newNode }
  nodeEditVisible.value = true
}

/** 节点编辑确认 */
const handleNodeEditConfirm = (nodeData) => {
  const index = approvalNodes.value.findIndex((node) => node.id === nodeData.id)
  if (index !== -1) {
    approvalNodes.value[index] = { ...nodeData }
  }

  nodeEditVisible.value = false
  ElMessage.success('节点配置保存成功')
}

/** 取消操作 */
const handleCancel = () => {
  router.go(-1)
}

/** 确定操作 */
const handleConfirm = async () => {
  // 验证所有节点都有审批人
  const invalidNodes = approvalNodes.value.filter((node) => {
    if (node.approverType === 'user') {
      return !node.approverUsers || node.approverUsers.length === 0
    } else if (node.approverType === 'role') {
      return !node.approverRole
    } else if (node.approverType === 'department') {
      return !node.approverDepartment
    }
    return true
  })

  if (invalidNodes.length > 0) {
    ElMessage.warning('存在未配置审批人的节点，请检查后重新提交')
    return
  }

  try {
    // 显示确认弹窗
    await ElMessageBox.confirm(
      '确认发布审批流程?\n若存在待审批的流程,将根据新版本流程重新分配审批任务',
      '确认发布',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )

    // 准备提交的数据
    const submitData = {
      processInfo: { ...processInfo },
      approvalNodes: approvalNodes.value
    }

    // 这里应该调用API保存流程配置
    console.log('保存流程配置:', submitData)
    ElMessage.success('流程配置保存成功')

    // 返回上一页
    router.go(-1)
  } catch {
    // 用户取消操作
    console.log('用户取消发布流程')
  }
}

/** 组件卸载时重置状态 */
onUnmounted(() => {
  selectedNodeId.value = null
  nodeEditVisible.value = false
  nodeIdCounter = 1
})
</script>

<style lang="scss" scoped>
.process-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-actions {
  display: flex;
  gap: 10px;
}

.process-info {
  .info-item {
    margin-bottom: 8px;

    .label {
      font-weight: 500;
      color: #666;
      margin-right: 8px;
    }

    .value {
      color: #333;
      font-weight: 600;
    }
  }
}

.process-config {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.flowchart-container {
  overflow-x: auto;
  padding: 20px 0;
}

.flowchart {
  display: flex;
  align-items: center;
  min-width: 800px;
  gap: 20px;
}

.node-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.node {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 120px;
  height: 60px;
  border-radius: 8px;
  font-weight: 500;
  position: relative;
  cursor: pointer;
  transition: all 0.3s ease;

  &.start-node {
    background: #909399;
    color: white;
    border-radius: 50%;
    width: 60px;
    height: 60px;
  }

  &.approval-node {
    background: white;
    border: 2px solid #e4e7ed;
    color: #333;

    &:hover {
      border-color: #409eff;
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
    }

    &.active {
      border-color: #67c23a;
      box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
    }

    .node-actions {
      width: 100%;
      align-items: center;
      justify-content: space-around;
      position: absolute;
      top: -20px;
      left: 50%;
      transform: translateX(-50%);
      display: none;
    }

    &:hover .node-actions {
      display: flex;
    }
  }

  &.end-node {
    background: #606266;
    color: white;
    border-radius: 50%;
    width: 60px;
    height: 60px;
  }
}

.add-node {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 120px;
  height: 60px;
  border: 2px dashed #c0c4cc;
  border-radius: 8px;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    border-color: #409eff;
    color: #409eff;
    background: #f0f9ff;
  }

  .el-icon {
    font-size: 20px;
    margin-bottom: 4px;
  }

  span {
    font-size: 12px;
  }
}

.arrow {
  width: 40px;
  height: 2px;
  background: #606266;
  position: relative;

  &::after {
    content: '';
    position: absolute;
    right: -8px;
    top: -4px;
    width: 0;
    height: 0;
    border-left: 8px solid #606266;
    border-top: 5px solid transparent;
    border-bottom: 5px solid transparent;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .process-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .flowchart {
    flex-direction: column;
    gap: 30px;
  }

  .node-container {
    flex-direction: column;

    .arrow {
      width: 2px;
      height: 40px;

      &::after {
        right: -4px;
        bottom: -8px;
        top: auto;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 8px solid #606266;
        border-bottom: none;
      }
    }
  }
}
</style>
